import type { FileItem } from '@douyinfe/semi-ui/lib/es/upload';

/**
 * @function readImgFileSrc
 * @description 读取图片文件的 src Base64 路径 
 */
export function readImgFileSrc(file: File) {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = () => {
      if (typeof reader.result === 'string') {
        resolve(reader.result);
      } else {
        reject('读取文件失败');
      }
    };
    reader.onerror = (error) => {
      reject(error);
    };

    reader.readAsDataURL(file);
  });
}

/**
 * @function getImgFileItem
 * @description 生成图片文件项 `fileItem`
 */
export function getImgFileItem(img: string): FileItem {
  const ts = Date.now();

  return {
    uid: ts.toString(),
    name: `${ts}.png`,
    status: 'success',
    url: img,
    size: '-KB',
  };
}

/**
 * @function debounce
 * @description 防抖函数
 * @param fn 需要防抖处理的函数
 * @param delay 延迟时间
 * @return 返回一个经过防抖处理的函数
 */
export function debounce<T extends Function>(fn: T, delay: number = 300) {
  let timer: NodeJS.Timeout | null = null;

  return function (...args: any[]) {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    timer = setTimeout(() => {
      fn(...args);

      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
    }, delay);
  }
}
